<script setup>
import { ref, computed } from "vue";
import bag from "../assets/mybag/bag-container.png";
import emptyAdd from "../assets/myAds/emptyAdd.png";
import { http } from "../services/service";
import { useRouter } from "vue-router";
import { covers } from "../enums/cover";

import { useUserStore } from "../store/index";
import { useI18n } from "vue-i18n";
const i18nUse = useI18n();
const router = useRouter();
const store = useUserStore();

const back = () => {
  router.push("/assets");
};
const value = ref("");
const value1 = ref("");
const fieldValue = ref();
const cardType = ref();
const choseCard = () => {
  router.push({ path: "/myBag", query: { type: "sell" } });
};
const showPicker = ref(false);

const cardListDto = ref([]);

const getCardList = () => {
  http.get(`/api/v1/center/getAppCardTypeList`).then(
    (response) => {
      const data = response?.data?.data;
      if (response?.data.code === 200) {
        const map = {
          1: i18nUse.t("upperFour"),
          2: i18nUse.t("middleFour"),
          3: i18nUse.t("lowerFour"),
        };
        cardListDto.value = data.map((e) => {
          return {
            ...e,
            text: map[e.id],
            value: e.id,
          };
        });
      }
    },
    () => {}
  );
};
const active = ref(0);
const rate = ref();
getCardList();
const onConfirm = ({ selectedOptions }) => {
  showPicker.value = false;
  fieldValue.value = selectedOptions[0].text;
  cardType.value = selectedOptions[0].value;
  rate.value = `${selectedOptions[0].cardGrowthRate * 100}%`;
};

const price = ref("");

const sellCard = () => {
  http
    .get(
      `/api/v1/center/pushAdBuy?telegramId=${store.getUser?.telegramId}&cardTypeId=${cardType.value}&currentPriceLimit=${price.value}`
    )
    .then(
      (response) => {
        if (response?.data.code === 200) {
          showToast(i18nUse.t("publish"));
          router.push({ path: "/trade", query: { fromAds: "sell" } });
        } else {
          showToast(response?.data.message);
        }
      },
      () => {}
    );
};

const publishCard = () => {
  http
    .get(
      `/api/v1/center/pushAdSell?telegramId=${store.getUser?.telegramId}&userCardId=${sellCardDetail.value.id}`
    )
    .then(
      (response) => {
        if (response?.data.code === 200) {
          showToast(i18nUse.t("publish"));
          router.push({ path: "/trade", query: { fromAds: "buy" } });
        } else {
          showToast(response?.data.message);
        }
      },
      () => {}
    );
};

const background = `url(${bag})`;
const from = router.currentRoute.value.query.from;
const getCardCover = (card) => {
  return covers[card.cardId]?.cover;
};
const sellCardDetail = ref(null);
const currentPrice = ref();
const rate2 = ref();
const turnover = ref();
if (from) {
  active.value = 1;
  sellCardDetail.value = JSON.parse(
    router.currentRoute.value.query.cardInfo
  )?.card;
  currentPrice.value = sellCardDetail.value?.currentPrice;
  turnover.value = sellCardDetail.value?.turnoverNumber;
  rate2.value = `${sellCardDetail.value?.cardGrowthRate * 100}%`;
}

const isPriceError = computed(() => {
  const cp = Number(price.value);
  return cp < 1 || cp > 500;
});

</script>

<template>
  <div class="container">
    <div class="title">
      <van-icon
        name="arrow-left"
        class="icon-left"
        size="25"
        @click="back()"
      />{{ $t("myAds") }}
    </div>
    <div class="container-tab">
      <van-tabs
        v-model:active="active"
        :background="background"
        color="#fff"
        title-active-color="#fff"
        title-inactive-color="#9699A2"
      >
        <van-tab :title="$t('buy')">
          <div class="withDraw">
            <van-field
              v-model="fieldValue"
              :label="$t('selectCards')"
              :placeholder="$t('please_choose')"
              readonly="readonly"
              @click="showPicker = true"
            />
            <van-popup v-model:show="showPicker" round position="bottom">
              <van-picker
                :columns="cardListDto"
                :confirm-button-text="$t('confirm')"
                :cancel-button-text="$t('cancel')"
                @cancel="showPicker = false"
                @confirm="onConfirm"
              />
            </van-popup>
            <van-field
              v-model="rate"
              :label="$t('ratePer')"
              placeholder=""
              :disabled="true"
              label-width="150px"
            />
            <van-field
              v-model="price"
              type="number"
              name="range"
              :label="$t('priceRange')"
              @change="handleChange"
              label-width="150px"
            />
            <div style="color: #ffab00; text-align: center" v-if="price">
              {{ $t("price_warning") }} 1-{{ price }}
            </div>
          </div>
          <div class="confirm">
            <van-button
              type="primary"
              block
              @click="sellCard()"
              :disabled="!price || !fieldValue"
              >{{ $t("publish_title") }}
            </van-button>
          </div>
        </van-tab>
        <van-tab :title="$t('sell')">
          <div class="img-container" v-if="!sellCardDetail">
            <img :src="emptyAdd" alt="" />
          </div>
          <div class="img-container" v-if="sellCardDetail">
            <img :src="getCardCover(sellCardDetail)" alt="" />
          </div>
          <span
            style="color: #4a61f9"
            class="container-chose-card"
            @click="choseCard()"
          >
            {{ $t("selectCards") }} <van-icon name="arrow" color="#4a61f9" />
          </span>
          <div class="withDraw">
            <van-field
              v-model="currentPrice"
              label-width="150px"
              :disabled="true"
              :label="$t('currentPrice')"
              placeholder=""
            />
            <van-field
              v-model="rate2"
              label-width="150px"
              :disabled="true"
              :label="$t('inflationPer')"
              placeholder=""
            />
            <van-field
              v-model="turnover"
              :disabled="true"
              label-width="150px"
              :label="$t('currentChange')"
              placeholder=""
            />
          </div>
          <div class="confirm">
            <van-button
              type="primary"
              block
              @click="publishCard()"
              :disabled="!sellCardDetail"
              >{{ $t("publish_title") }}
            </van-button>
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<style scoped lang="less">
.confirm {
  width: 70%;
  margin:20px auto;

  button {
    background-image: linear-gradient(to right, #9ba8ff, #4a61f9);
    border-radius: 10px;
  }
}
.container-chose-card {
  text-align: center;
  display: inline-block;
  margin-top: 20px;
  width: 100%;
  cursor: pointer;
}

.img-container {
  width: 164px;
  height: 182px;
  margin: 20px auto;
  border-radius: 10px;
  //   background-color: rgba(255, 255, 255, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;

  img {
    width: 100%;
    height: 100%;
  }
}

.container {
  background: url("../assets/home-page-bg.png");
  width: 100%;
  min-height: 100vh;
  padding-bottom: 100px;
  background-position: center center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
  color: #fff;
}

.title {
  .icon-left {
    position: absolute !important;
    left: 16px;
    top: 8px;
    cursor: pointer;
  }

  font-size: 17px;
  text-align: center;
  width: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 44px;
}

.container-tab {
  margin-top: 30px;
}

.withDraw {
  width: 311px;
  margin: 40px auto 0 auto;
  background: rgba(44, 47, 61, 0.7);
  border-radius: 10px;
  border: 1px solid #9aa7ff;
  min-height: 40px;

  .van-cell {
    background-color: unset !important;
    color: #fff !important;

    .van-cell__title {
      color: #fff !important;
    }
  }

  .van-cell__title {
    color: #fff !important;
  }
}
</style>
